package cn.com.gzheroli.bfw.web.system.controler.core;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;


import cn.com.gzheroli.bfw.pojo.base.TSFunction;
import cn.com.gzheroli.bfw.pojo.base.TSRoleFunction;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.bfw.service.RandCodeService;
import cn.com.gzheroli.bfw.service.SessionService;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.ComboTree;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.constant.Globals;
import cn.com.gzheroli.core.extend.datasource.DataSourceContextHolder;
import cn.com.gzheroli.core.extend.datasource.DataSourceType;
import cn.com.gzheroli.core.manager.Client;
import cn.com.gzheroli.core.manager.ClientManager;
import cn.com.gzheroli.core.util.ContextHolderUtils;
import cn.com.gzheroli.core.util.IdWorker;
import cn.com.gzheroli.core.util.IpUtil;
import cn.com.gzheroli.core.util.LogUtil;
import cn.com.gzheroli.core.util.MenuBean;
import cn.com.gzheroli.core.util.PasswordUtil;
import cn.com.gzheroli.core.util.PropertiesUtil;
import cn.com.gzheroli.core.util.oConvertUtils;
import cn.com.gzheroli.rabbitmq.service.log.LogService;
import cn.com.gzheroli.service.bfw.UserService;
import cn.com.gzheroli.tag.vo.easyui.ZNodes;


/**
 * 登陆初始化控制器
 * 
 * 
 */
@Controller
@RequestMapping("/loginController")
public class LoginController {
	private Logger log = Logger.getLogger(LoginController.class);
	private static int  exp=1800;
	@Autowired
    private SpringRedisCache cache;
	@Autowired
	private SystemService systemService;
	//@Resource
	//@Reference(version = "1.0.0", interfaceClass = UserService.class, timeout = 2000, check = true, lazy = false)
	@Autowired
	private UserService userService;
	@Autowired
	private CommonService commonService;
	@Autowired
	private LogService logService;
	@Autowired
	private SessionService sessionService;
	@Autowired
	RandCodeService randCodeService;
	@Value("${isNeedRandCode}") 
	private String isNeedRandCode;
	private String message = null;
	private Map<Integer, List<TSFunction>> shortcutFunctionMap = null;



	@RequestMapping(params = "goPwdInit")
	public String goPwdInit() {
		return "login/pwd_init";
	}

	/**
	 * admin账户密码初始化
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "pwdInit")
	public ModelAndView pwdInit(HttpServletRequest request) {
		ModelAndView modelAndView = null;
		TSUser user = new TSUser();
		user.setUserName("admin");
		String newPwd = "123456";
		userService.pwdInit(user, newPwd);
		modelAndView = new ModelAndView(new RedirectView(
				"loginController.do?login"));
		return modelAndView;
	}

	/**
	 * 修改密码
	 * @param user 
	 */
	@RequestMapping(params="updatePwd")
	@ResponseBody
	public AjaxJson UpdatePwd(HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		//TSUser tuser = ResourceUtil.getSessionUserName();
		//TSUser tuser =cache.getCache(request.getSession().getId(), Client.class).getUser();
		String token = request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		TSUser tuser = client.getUser();
		String id = oConvertUtils.getString(request.getParameter("id"));
		String password = oConvertUtils.getString(request.getParameter("password"));//输入的原密码
		String newpassword = oConvertUtils.getString(request.getParameter("newpassword"));//新密码
		String passwordOK=oConvertUtils.getString(request.getParameter("passwordOK"));//再输一次新密码
		String oldpassword=oConvertUtils.getString(tuser.getPassword());//原密码
		/*if(!newpassword.equals(passwordOK)){
			j.setSuccess(false);
			j.setMsg("两次输入的密码不一致！");
			System.out.println("两次输入的密码不一致！");
			}*/
//			else{//两次密码一致
		//输入的数据转化为这个，可以直接和tuser.getpassword()相比，PasswordUtil.encrypt(user.getUserName(), password,PasswordUtil.getStaticSalt());
		String pString = PasswordUtil.encrypt(tuser.getUserName(), password,PasswordUtil.getStaticSalt());
				if (pString.equals(tuser.getPassword())) {//原密码正确
					tuser.setPassword(PasswordUtil.encrypt(tuser.getUserName(),newpassword, PasswordUtil.getStaticSalt()));
					commonService.updateEntitie(tuser);
					j.setSuccess(true);
					j.setMsg("修改成功");
					System.out.println("修改成功");
			} else {//原密码不正确
			if (!pString.equals(tuser.getPassword())) {
				j.setSuccess(false);
				j.setMsg("原密码不正确");
				System.out.println("原密码不正确");
			} 
		}
		

		return j;
	}
	@RequestMapping(params = "getRandCode")
	@ResponseBody
	public AjaxJson getRandCode(HttpServletRequest req) throws IOException {
		AjaxJson j=new AjaxJson();
		String tokenId = req.getParameter("tokenId");
		String randCode=randCodeService.genRandCodePicBase64(tokenId);
		j.setObj(randCode);
		j.setMsg("获取验证码成功!");
		j.setSuccess(true);
		return j;
	}
	/**
	 * 检查用户名称
	 * 
	 * @param user
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "checkuser")
	@ResponseBody
	public AjaxJson checkuser(TSUser user, HttpServletRequest req) {
		HttpSession session = ContextHolderUtils.getSession();
		DataSourceContextHolder
				.setDataSourceType(DataSourceType.dataSource_jeecg);
		AjaxJson j = new AjaxJson();
		// update-begin--Author:zhangguoming Date:20140226 for：添加验证码
		String randCode = req.getParameter("randCode");
		String tokenId = req.getParameter("tokenId");
		String userName=new String(Base64.decodeBase64(user.getUserName()));
		String password=new String(Base64.decodeBase64(user.getPassword()));
		user.setUserName(userName);
		user.setPassword(password);
		//PropertiesUtil p = new PropertiesUtil("db.properties");
		//String isNeedRandCode=p.readProperty("isNeedRandCode")==null?"true":p.readProperty("isNeedRandCode");
		//String isNeedRandCode=Config.isNeedRandCode;
		//0:pc app:手机
		String clientType = req.getHeader("clientType")==null?"pc": req.getHeader("clientType");
		/**/ 
		if(clientType.equals("pc")&&isNeedRandCode.equals("true")){
			  if (StringUtils.isEmpty(randCode)) { 
				  j.setMsg("请输入验证码");
				  j.setSuccess(false); 
			  } else if(!randCode.equalsIgnoreCase(cache.getCache(tokenId, String.class))) { 
				  // todo"randCode"和验证码servlet中该变量一样，通过统一的系统常量配置比较好，暂时不知道系统常量放在什么地方合适
				  j.setMsg("验证码错误！");
				  j.setSuccess(false); 
			  }
		}else{
		 
			/*if( sessionService.isLockUser(userName) ){
	        	
	         	j.setMsg("该用户被锁,请等30分钟后再登录！"); //---------------------- 修改  ------------------
	            j.setSuccess(false);
	            return j;
	        }*/
			TSUser u = userService.checkUserExits(user);
			if (u != null) {
				sessionService.unlockUser(userName);//---------------------- 修改  ------------------
				
				// if (user.getUserKey().equals(u.getUserKey())) {
				if (true) {
					message = "用户: " + userName + "["
							+ "" + "]" + "登录成功";
					Map paraMap=LogUtil.logReqMap(req);
					String broswer=paraMap.get("broswer")==null?"":paraMap.get("broswer").toString();
					Client client = new Client();
					client.setIp(IpUtil.getIpAddr(req));
					client.setLogindatetime(new Date());
					client.setUser(u);
					client.setLoginMethod("1");
					client.setBroswer(broswer);
					/*ClientManager.getInstance().addClinet(session.getId(),
							client);*/
					//cache.putCache(session.getId(), client);
					String token=req.getHeader("token");
					if(token==null||token.trim().equals(""))
						token=u.getId()+"_"+IdWorker.getFlowIdWorkerInstance().nextIdStr();
					
					paraMap.put("token", token);
					paraMap.put("clientType", clientType);
					session.setAttribute(token, client);
					sessionService.changeLogin4Me(client,token,clientType);  // 对多人 同时登录控制  --------------------------修改了------------------------------
					Map attributes=new HashMap();
					
					attributes.put("sessionId", req.getSession().getId());
					attributes.put("token",token );
					attributes.put("expireTime", cache.getExpireTime(token));
					j.setAttributes(attributes);
					// 添加登陆日志
					logService.addLogLogin(message, Globals.Log_Leavel_INFO,null,paraMap);

				} else {
					j.setMsg("请检查U盾是否正确");
					j.setSuccess(false);
				}
			}else {
				j.setMsg("用户名或密码错误!,密码错误3次,帐号将被锁定");
				j.setSuccess(false);
				sessionService.addCount(user.getUserName());  //---------------------- 修改  ------------------
            	logService.addLog(user.getUserName()+"登录失败", 
            			Globals.Log_Type_EXIT, null,LogUtil.logReqMap(req));
      
			}
		}
		return j;
	}
	/**
	 * 用户登录
	 * 
	 * @param user
	 * @param request
	 * @param session
	 * @return
	 */
	/*@RequestMapping(params = "vlogin")
	@ResponseBody
	public AjaxJson vlogin(ModelMap modelMap,HttpServletRequest request,HttpServletResponse response) {
		//TSUser user = ResourceUtil.getSessionUserName();
		AjaxJson j = new AjaxJson();
		Client client =cache.getCache(request.getSession().getId(), Client.class);
		if(client==null) {
			j.setMsg("");
			return j;
		}
		TSUser user =client.getUser();
		String roles = "";
		if (user != null) {
			String departName="";
			request.setAttribute("roleName", roles);
			request.setAttribute("userName", user.getUserName());
			request.setAttribute("userRealName", user.getRealName());
			request.setAttribute("userdepartName",departName );//bumen
			request.setAttribute("email", user.getEmail());
			request.setAttribute("officePhone", user.getOfficePhone());
			request.setAttribute("id", user.getId());
			request.getSession().setAttribute("CKFinder_UserRole", "admin");
			request.getSession().setAttribute("userRealName",user.getRealName());
			request.getSession().setAttribute("userdepartName", departName);//
			request.getSession().setAttribute("email", user.getEmail());
			request.getSession().setAttribute("officePhone", user.getOfficePhone());
			request.getSession().setAttribute("id", user.getId());
			j.setObj(user);
		}
		return j;
	}*/
	/**
	 * 用户登录
	 * 
	 * @param user
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(params = "login")
	public String login(ModelMap modelMap,HttpServletRequest request,HttpServletResponse response) {
		DataSourceContextHolder
				.setDataSourceType(DataSourceType.dataSource_jeecg);
		//TSUser user = ResourceUtil.getSessionUserName();
		String token = request.getHeader("token");
		Client client =cache.getCache(token, Client.class);
		if(client==null) {
			return "login/login";
		}
		TSUser user =client.getUser();
		String roles = "";
		if (user != null) {
			String departName="";
			/*if(user.getTSDepart()!=null)
				departName=user.getTSDepart().getDepartname();*/
			request.setAttribute("roleName", roles);
			request.setAttribute("userName", user.getUserName());
			request.setAttribute("userRealName", user.getRealName());
			request.setAttribute("userdepartName",departName );//bumen
			request.setAttribute("email", user.getEmail());
			request.setAttribute("officePhone", user.getOfficePhone());
			request.setAttribute("id", user.getId());
			request.getSession().setAttribute("CKFinder_UserRole", "admin");
			request.getSession().setAttribute("userRealName",user.getRealName());
			request.getSession().setAttribute("userdepartName", departName);//
			request.getSession().setAttribute("email", user.getEmail());
			request.getSession().setAttribute("officePhone", user.getOfficePhone());
			request.getSession().setAttribute("id", user.getId());
			// 获取一级菜单列表
			request.setAttribute("primaryMenuList", getPrimaryMenu(user.getId()));
			
			// 默认风格
			String indexStyle = "shortcut";
			indexStyle = request.getParameter("indexStyle") == null ? "heroli"
					: request.getParameter("indexStyle");
			// indexStyle = "kitstyle";
			Cookie[] cookies = request.getCookies();
			for (Cookie cookie : cookies) {
				if (cookie == null || StringUtils.isEmpty(cookie.getName())) {
					continue;
				}
				if (cookie.getName().equalsIgnoreCase("INDEXSTYLE")) {
					indexStyle = cookie.getValue();
				}
			}
			Cookie cookie = new Cookie("INDEXSTYLE", indexStyle);
			//设置cookie有效期为一个月
			cookie.setMaxAge(3600*24*30);
			response.addCookie(cookie);
				if("ace".equals(indexStyle)||"diy".equals(indexStyle)||"acele".equals(indexStyle)){
					/*List<MenuBean> menulist = new ArrayList();
					List<Map<String,Object>> firstmenulist=getMenu(user.getId(),"0","1","0","");
						for (Map<String,Object> fun : firstmenulist) {

							MenuBean menuBean = new MenuBean();
							menuBean.setNo(fun.get("ID").toString());
							menuBean.setName(fun.get("FUNCTION_NAME")==null?"":fun.get("FUNCTION_NAME").toString());
							menuBean.setOrderNum(fun.get("FUNCTION_ORDER")==null?"":fun.get("FUNCTION_ORDER").toString());
							menuBean.setUrl(fun.get("FUNCTION_URL")==null?"":fun.get("FUNCTION_URL").toString());
							menuBean.setIsView("Y");
							menuBean.setModelId(null);
							menuBean.setIcon(fun.get("FRONT_ICON")==null?"":fun.get("FRONT_ICON").toString());
							menuBean.setIsShortcut(fun.get("IS_SHORTCUT")==null?"":fun.get("IS_SHORTCUT").toString());
							menuBean.setShortcutClass(fun.get("SHORTCUT_CLASS")==null?"":fun.get("SHORTCUT_CLASS").toString());
							menuBean.setIconClas(fun.get("ICON_CLAS")==null?"":fun.get("ICON_CLAS").toString());
							menuBean.setIsMenu(fun.get("IS_MENU")==null?"":fun.get("IS_MENU").toString());
							menuBean.setIconId(fun.get("ICON_ID")==null?"":fun.get("ICON_ID").toString());
							menuBean.setIconPath(fun.get("PATH")==null?"":fun.get("PATH").toString());
							List childList = new ArrayList();
							menuBean.setChildren(getChild(user.getId(),fun, 1, childList));
							menuBean.setParentId("");
							menulist.add(menuBean);
						}
					request.setAttribute("menuMap", menulist);*/
				}
			// 要添加自己的风格，复制下面三行即可
			if (StringUtils.isNotEmpty(indexStyle)
					&& indexStyle.equalsIgnoreCase("bootstrap")) {
				return "main/bootstrap_main";
			}
			if (StringUtils.isNotEmpty(indexStyle)
					&& indexStyle.equalsIgnoreCase("shortcut")) {
				return "main/shortcut_main";
			}
			if (StringUtils.isNotEmpty(indexStyle)
					&& indexStyle.equalsIgnoreCase("heroli")) {
				return "main/aceindex";
			}
			if (StringUtils.isNotEmpty(indexStyle)
					&& indexStyle.equalsIgnoreCase("inspini")) {
				return "main/index";
			}
			if (StringUtils.isNotEmpty(indexStyle)
					&& indexStyle.equalsIgnoreCase("ace")) {
				return "main/ace_main";
			}
			return "main/main";
		} else {
			return "login/login";
		}

	}

	/**
	 * 退出系统
	 * 
	 * @param user
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "logout")
	public ModelAndView logout(HttpServletRequest request) {
		HttpSession session = ContextHolderUtils.getSession();
		//TSUser user = ResourceUtil.getSessionUserName();
		String token = request.getHeader("token");
		Client client =cache.getCache(token, Client.class);
		TSUser user =client.getUser();
		shortcutFunctionMap = null;
		logService.addLogLogin("用户" + user.getUserName() + "已退出",
				Globals.Log_Type_EXIT, null,LogUtil.logReqMap(request));
		ClientManager.getInstance().removeClinet(token);
		//cache.deleteCache(request.getSession().getId());
		sessionService.removeUserSession(token);
		ModelAndView modelAndView = new ModelAndView(new RedirectView(
				"loginController.do?login"));

		return modelAndView;
	}

	/**
	 * 菜单跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "left")
	public ModelAndView left(HttpServletRequest request) {
		//TSUser user = ResourceUtil.getSessionUserName();
		String token = request.getHeader("token");
		Client client =cache.getCache(token, Client.class);
		TSUser user =client.getUser();
		HttpSession session = ContextHolderUtils.getSession();
		// 登陆者的权限
		if (user.getId() == null) {
			session.removeAttribute(Globals.USER_SESSION);
			return new ModelAndView(
					new RedirectView("loginController.do?login"));
		}

		request.setAttribute("menuMap", getFunctionMap(user.getId()));
		return new ModelAndView("main/left");
	}

	/**
	 * 获取权限的map
	 * 
	 * @param user
	 * @return
	 */
	private List<Map<String,Object>> getFunctionMap(String userId) {
		Map<Integer, List<TSFunction>> functionMap = new HashMap<Integer, List<TSFunction>>();
		List<Map<String,Object>> firstMenuList=getMenu(userId,"0","1","0","","");
		return firstMenuList;
	}

	/**
	 * 获取用户菜单列表
	 * 
	 * @param user
	 * @return
	 */
	/*private Map<String, TSFunction> getUserFunction(TSUser user) {
		HttpSession session = ContextHolderUtils.getSession();
		Client client = ClientManager.getInstance().getClient(session.getId());
		if (client.getFunctions() == null) {
			Map<String, TSFunction> loginActionlist = new HashMap<String, TSFunction>();
			List<TSRoleFunction> roleFunctionList = systemService
					.findByQueryString("select rf from TSRoleFunction rf,TSRoleUser ru where rf.TSRole.id=ru.TSRole.id and rf.TSFunction.isMenu='1' and ru.TSUser.id='"
							+ user.getId() + "'");
			for (TSRoleFunction roleFunction : roleFunctionList) {
				TSFunction function = roleFunction.getTSFunction();
				loginActionlist.put(function.getId(), function);
			}
			client.setFunctions(loginActionlist);
		}
		return client.getFunctions();
	}*/

	/**
	 * 首页跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "home")
	public ModelAndView home(HttpServletRequest request) {
		return new ModelAndView("main/home");
	}

	/**
	 * 无权限页面提示跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "noAuth")
	public ModelAndView noAuth(HttpServletRequest request) {
		return new ModelAndView("common/noAuth");
	}

	/**
	 * @Title: top
	 * @Description: bootstrap头部菜单请求
	 * @param request
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping(params = "top")
	public ModelAndView top(HttpServletRequest request) {
		//TSUser user = ResourceUtil.getSessionUserName();
		String token = request.getHeader("token");
		Client client =cache.getCache(token, Client.class);
		TSUser user =client.getUser();
		HttpSession session = ContextHolderUtils.getSession();
		// 登陆者的权限
		if (user.getId() == null) {
			session.removeAttribute(Globals.USER_SESSION);
			return new ModelAndView(
					new RedirectView("loginController.do?login"));
		}
		request.setAttribute("menuMap", getFunctionMap(user.getId()));
		return new ModelAndView("main/bootstrap_top");
	}

	/**
	 * @Title: top
	 * @author gaofeng
	 * @Description: shortcut头部菜单请求
	 * @param request
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping(params = "shortcut_top")
	public ModelAndView shortcut_top(HttpServletRequest request) {
		//TSUser user = ResourceUtil.getSessionUserName();
		String token = request.getHeader("token");
		Client client =cache.getCache(token, Client.class);
		TSUser user =client.getUser();
		HttpSession session = ContextHolderUtils.getSession();
		// 登陆者的权限
		if (user.getId() == null) {
			session.removeAttribute(Globals.USER_SESSION);
			return new ModelAndView(
					new RedirectView("loginController.do?login"));
		}
		request.setAttribute("menuMap", getFunctionMap(user.getId()));
		return new ModelAndView("main/shortcut_top");
	}

	/**
	 * @Title: top
	 * @Description: shortcut头部菜单请求
	 * @param request
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping(params = "shortcut_leftmenu")
	public ModelAndView shortcut_leftmenu(HttpServletRequest request) {
		//TSUser user = ResourceUtil.getSessionUserName();
		String token = request.getHeader("token");
		Client client =cache.getCache(token, Client.class);
		TSUser user =client.getUser();
		HttpSession session = ContextHolderUtils.getSession();
		// 登陆者的权限
		if (user.getId() == null) {
			session.removeAttribute(Globals.USER_SESSION);
			return new ModelAndView(
					new RedirectView("loginController.do?login"));
		}
		request.setAttribute("menuMap", getFunctionMap(user.getId()));
		return new ModelAndView("main/shortcut_top");
	}

	/**
	 * @Title: top
	 * @author:gaofeng
	 * @Description: shortcut头部菜单一级菜单列表，并将其用ajax传到页面，实现动态控制一级菜单列表
	 * @param request
	 * @return AjaxJson
	 * @throws
	 */
	public String getPrimaryMenu(String userId) {
		String roles="";
		// 获取一级菜单列表
		List<Map<String,Object>> functions=new ArrayList<Map<String,Object>>();
		if (shortcutFunctionMap != null) {

			// 将更新前的菜单数据传过来
			//functionMap = shortcutFunctionMap;
		} else {
			
			/*for (TSRoleUser ru : rUsers) {
				TSRole role = ru.getTSRole();
				roles=roles+","+role.getId();
			}
			if(roles.startsWith(","))
				roles=roles.substring(1);*/
			//functions = getPrimaryMenuBase(roles);
			functions=getMenu(userId,"1","1","0","","");
		}

		String floor = "";
		//List<TSFunction> primaryMenu = null;
		//Iterator<Entry<Integer, List<TSFunction>>> it = functionMap.entrySet().iterator();
		//while (it.hasNext()) {
		for(Map funcMap:functions){
			//Map.Entry pairs = (Map.Entry) it.next();
			//primaryMenu = (List<TSFunction>) pairs.getValue();
			//String funcname=(String)funcMap.get("FUNCTION_NAME");
			String funcname=(String)funcMap.get("functionName");
			//for (TSFunction function : primaryMenu) {
				// com.gzkit.core.util.LogUtil.info(function.getFunctionName());
				// com.gzkit.core.util.LogUtil.info(function.getFunctionLevel());
				//if (function.getFunctionLevel() == 0) {

					if ("Online 开发".equals(funcname)) {

						floor += " <li><img class='imag1' src='plug-in/login/images/online.png' /> "
								+ " <img class='imag2' src='plug-in/login/images/online_up.png' style='display: none;' />"
								+ " </li> ";
					} else if ("统计查询".equals(funcname)) {

						floor += " <li><img class='imag1' src='plug-in/login/images/guanli.png' /> "
								+ " <img class='imag2' src='plug-in/login/images/guanli_up.png' style='display: none;' />"
								+ " </li> ";
					} else if ("系统管理".equals(funcname)) {

						floor += " <li><img class='imag1' src='plug-in/login/images/xtgl.png' /> "
								+ " <img class='imag2' src='plug-in/login/images/xtgl_up.png' style='display: none;' />"
								+ " </li> ";
					} else if ("常用示例".equals(funcname)) {

						floor += " <li><img class='imag1' src='plug-in/login/images/cysl.png' /> "
								+ " <img class='imag2' src='plug-in/login/images/cysl_up.png' style='display: none;' />"
								+ " </li> ";
					} else if ("系统监控".equals(funcname)) {

						floor += " <li><img class='imag1' src='plug-in/login/images/xtjk.png' /> "
								+ " <img class='imag2' src='plug-in/login/images/xtjk_up.png' style='display: none;' />"
								+ " </li> ";
					} else {
						// 其他的为默认通用的图片模式
						String s = "";
						if (funcname.length() >= 5
								&& funcname.length() < 7) {
							s = "<div style='width:67px;position: absolute;top:40px;text-align:center;color:#909090;font-size:12px;'><span style='letter-spacing:-1px;'>"
									+ funcname
									+ "</span></div>";
						} else if (funcname.length() < 5) {
							s = "<div style='width:67px;position: absolute;top:40px;left:0px;text-align:center;color:#909090;font-size:12px;'>"
									+ funcname + "</div>";
						} else if (funcname.length() >= 7) {
							s = "<div style='width:67px;position: absolute;top:40px;text-align:center;color:#909090;font-size:12px;'><span style='letter-spacing:-1px;'>"
									+ funcname
											.substring(0, 6) + "</span></div>";
						}
						floor += " <li style='position: relative;'><img class='imag1' src='plug-in/login/images/default.png' /> "
								+ " <img class='imag2' src='plug-in/login/images/default_up.png' style='display: none;' />"
								+ s + "</li> ";
					}
				//}
			//}
		}

		return floor;
	}

	/**
	 * 获取指定类型的菜单信息
	 * @param userId 用户编号
	 * @param isFront 是否前台显示
	 * @param isMenu 是否菜单
	 * @param level 功能级别
	 * @return
	 */
	public List<Map<String,Object>> getMenu(String userId,String  isFront,String isMenu,String level,String parentId,String isVueComponent) {

		// 获取一级菜单列表
		String sql="select distinct f.id,FUNCTION_NAME,FUNCTION_URL,FUNCTION_LEVEL,FUNCTION_ORDER,IS_MENU,IS_FRONT,PARENT_ID,IS_SHORTCUT,SHORTCUT_CLASS,FRONT_ICON,COMPONENT_NAME ";
		sql+=",i.ICON_CLAS, i.PATH ";
		sql+=" from t_s_function f inner join t_s_role_function rf on f.id=rf.function_id inner join  t_s_role_user ru on rf.role_id=ru.role_id left join T_S_ICON i on f.ICON_ID=i.ID  ";
		sql+=" where  ru.user_id=#{userId}  ";
		sql+="and f.FUNCTION_LEVEL='"+level+"' ";
		if(isMenu!=null)
		sql+=" and f.IS_MENU='"+isMenu+"'";
		if(isFront!=null)
		sql+=" and f.IS_FRONT='"+isFront+"'";
		if(isVueComponent!=null&&isVueComponent.equals("1"))
			sql+=" and f.COMPONENT_NAME like '%,%'";
		if(parentId!=null&&!parentId.trim().equals(""))
			sql+=" and f.PARENT_ID='"+parentId+"'";
		//sql+=" and f.IS_FRONT='"+isFront+"'";
		sql+=" order by FUNCTION_ORDER";
		log.info(sql);
		Map para=new HashMap();
		para.put("userId", userId);
		return commonService.findForJdbc(sql,para );
	}

	@RequestMapping(params = "getZTreeMenu")
	@ResponseBody
	public void getZTreeMenu(HttpServletRequest req,
			HttpServletResponse response) throws IOException {
		String pId = req.getParameter("id");
		String pLevel = req.getParameter("pLevel") == null ? "0" : req
				.getParameter("pLevel");
		String sql = "";
		// DataSourceContextHolder.setDataSourceType(DataSourceType.dataSource_jeecg);
		AjaxJson j = new AjaxJson();
		String menustr = "";
		String userId = "";
		ZNodes znode = new ZNodes();
		znode.setPid(pId);
		if (pId == null || pId.trim().equals(""))
			znode.setPlevel(Integer.parseInt(pLevel));
		//TSUser user = ResourceUtil.getSessionUserName();
		//TSUser user=systemService.findByProperty(TSUser.class, "userName", "admin").get(0);
		TSUser user =cache.getCache(req.getSession().getId(), Client.class).getUser();
		userId = user.getId();
		List<ZNodes> menulist = this.userService.getUserMenu(znode, userId);
		List<ComboTree> comboTrees = new ArrayList<ComboTree>();
		for (ZNodes znodeBean : menulist) {
			String pid = znodeBean.getPid() == null ? "" : znodeBean.getPid();
			String url = znodeBean.getUrl() == null ? "" : znodeBean.getUrl();
			boolean isParent = znodeBean.getSubMenuCount() > 0 ? true : false;
			/*
			 * ComboTree tree=new ComboTree(); tree.setId(znodeBean.getId());
			 * tree.setText(znodeBean.getName());
			 * tree.setIconCls(znodeBean.getIcon()); Map attributes=new
			 * HashMap(); attributes.put("url", url); attributes.put("pid",
			 * pid); tree.setAttributes(attributes); comboTrees.add(tree);
			 */
			// menustr+=",{id:\'"+znodeBean.getId()+"\', pId:\'"+pid+"\', name:\'"+znodeBean.getName()+"\',url:\'"+url+"\',open:true}";
			menustr += ",{id:\'" + znodeBean.getId() + "\', pId:\'" + pid
					+ "\', name:\'" + znodeBean.getName() + "\',targetUrl:\'"
					+ url + "\',isParent:" + isParent + ",icon:'"
					+ znodeBean.getIcon() + "'}";
		}
		if (menustr.startsWith(","))
			menustr = menustr.substring(1);
		// j.setMsg("["+menustr+"]");
		// return j;
		// menustr=JSONObject.toJSONString(lstTree);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print("[" + menustr + "]");
		// return "["+menustr+"]";
		// return comboTrees;
	}

	@RequestMapping(params = "getUserMenu")
	@ResponseBody
	public AjaxJson getUserMenu(HttpServletRequest req,
			HttpServletResponse response) {
		String pId = req.getParameter("id");
		String isVueComponent = req.getParameter("isVueComponent");
		AjaxJson j = new AjaxJson();
		String userId = "";
		ZNodes znode = new ZNodes();
		znode.setPid(pId);
		String token = req.getHeader("token");
		Client client =cache.getCache(token, Client.class);
		//TSUser user = ResourceUtil.getSessionUserName();
		//TSUser user=systemService.findByProperty(TSUser.class, "userName", "admin").get(0);
		TSUser user =client.getUser();
		userId = user.getId();
		// List<ZNodes> menulist=this.userService.getUserMenu(znode, userId);
		//Map<Integer, List<TSFunction>> functionMap = getPrimaryMenuBase(user);
		//List<TSFunction> firstmenulist = functionMap.get(0);
		List<MenuBean> menulist = new ArrayList();
		//if (firstmenulist != null && !firstmenulist.isEmpty())
		List<Map<String,Object>> firstmenulist=getMenu(user.getId(),"0","1","0","",isVueComponent);
			for (Map<String,Object> fun : firstmenulist) {

				MenuBean menuBean = new MenuBean();
				menuBean.setNo(fun.get("id").toString());
				menuBean.setName(fun.get("functionName")==null?"":fun.get("functionName").toString());
				menuBean.setOrderNum(fun.get("functionOrder")==null?"":fun.get("functionOrder").toString());
				menuBean.setUrl(fun.get("functionUrl")==null?"":fun.get("functionUrl").toString());
				menuBean.setIsView("Y");
				menuBean.setModelId(null);
				menuBean.setIcon(fun.get("frontIcon")==null?"":fun.get("frontIcon").toString());
				menuBean.setIsShortcut(fun.get("isShortcut")==null?"":fun.get("isShortcut").toString());
				menuBean.setShortcutClass(fun.get("shortcutClass")==null?"":fun.get("shortcutClass").toString());
				menuBean.setIconClas(fun.get("iconClas")==null?"":fun.get("iconClas").toString());
				menuBean.setIsMenu(fun.get("isMenu")==null?"":fun.get("isMenu").toString());
				menuBean.setIconId(fun.get("iconId")==null?"":fun.get("iconId").toString());
				menuBean.setIconPath(fun.get("path")==null?"":fun.get("path").toString());
				menuBean.setComponentName(fun.get("componentName")==null?"":fun.get("componentName").toString());
				List childList = new ArrayList();
				menuBean.setChildren(getChild(user.getId(),fun, 1, childList,isVueComponent));
				menulist.add(menuBean);
			}

		Map attributes = new HashMap();
		attributes.put("userMenu", menulist);
		j.setAttributes(attributes);
		return j;
	}

	private List<MenuBean> getChild(String userId,Map<String,Object> parent, int level,
			List<MenuBean> menuList,String isVueComponent) {
		List<Map<String,Object>> list = getMenu(userId,"0","1",level+"",parent.get("id").toString(),isVueComponent);
		if (list != null && !list.isEmpty())
			for (Map<String,Object> fun : list) {
				String id=fun.get("id").toString();
				String functionname=fun.get("functionName")==null?"":fun.get("functionName").toString();
				int curlevel=fun.get("functionOrder")==null?level+1:Integer.parseInt(fun.get("functionOrder").toString());
				String functionurl=fun.get("functionUrl")==null?"":fun.get("functionUrl").toString();
				String FRONTICON=fun.get("frontIcon")==null?"":fun.get("frontIcon").toString();
				String ISSHORTCUT=fun.get("isShortcut")==null?"":fun.get("isShortcut").toString();
				String SHORTCUTCLASS=fun.get("shortcutClass")==null?"":fun.get("shortcutClass").toString();
				String parentfunctionid=fun.get("parentId")==null?"":fun.get("parentId").toString();
				
				String iconClas=fun.get("iconClas")==null?"":fun.get("iconClas").toString();
				String isMenu=fun.get("isMenu")==null?"":fun.get("isMenu").toString();
				String iconId=fun.get("iconId")==null?"":fun.get("iconId").toString();
				String iconPath=fun.get("path")==null?"":fun.get("path").toString();
				String componentName=fun.get("componentName")==null?"":fun.get("componentName").toString();
				List<Map<String,Object>> subList=getMenu(userId,"1","1",(curlevel+1)+"",id,isVueComponent);
					if (subList==null|| subList.isEmpty()) {
						MenuBean menuBean = new MenuBean();
						menuBean.setNo(id);
						menuBean.setName(functionname);
						menuBean.setOrderNum(curlevel+"");
						menuBean.setUrl(functionurl);
						menuBean.setIsView("Y");
						menuBean.setIcon(FRONTICON);
						menuBean.setModelId(null);
						menuBean.setChildren(new ArrayList());
						menuBean.setIsShortcut(ISSHORTCUT);
						menuBean.setShortcutClass(SHORTCUTCLASS);
						menuBean.setParentId(parentfunctionid);
						menuBean.setComponentName(componentName);
						menuBean.setIconId(iconId);
						menuBean.setIconPath(iconPath);
						menuBean.setIconClas(iconClas);
						menuBean.setIsMenu(isMenu);
						menuList.add(menuBean);
					} else {
						MenuBean menuBean = new MenuBean();
						menuBean.setNo(id);
						menuBean.setName(functionname);
						menuBean.setOrderNum(curlevel+"");
						menuBean.setUrl(functionurl);
						menuBean.setIsView("Y");
						menuBean.setIcon(FRONTICON);
						menuBean.setModelId(parentfunctionid);
						List childList = new ArrayList();
						menuBean.setChildren(getChild(userId,fun, curlevel + 1,childList,isVueComponent));
						menuBean.setIsShortcut(ISSHORTCUT);
						menuBean.setShortcutClass(SHORTCUTCLASS);
						menuBean.setParentId(parentfunctionid);
						menuBean.setIconId(iconId);
						menuBean.setIconPath(iconPath);
						menuBean.setIconClas(iconClas);
						menuBean.setIsMenu(isMenu);
						menuBean.setComponentName(componentName);
						menuList.add(menuBean);
					}
			}
		return menuList;
	}

	@RequestMapping(params = "goBackDeskManager")
	public String goBackDeskManager(HttpServletRequest request,
			HttpServletResponse response) {
		String token = request.getHeader("token");
		Client client =cache.getCache(token, Client.class);
		//TSUser user = ResourceUtil.getSessionUserName();
		TSUser user =client.getUser();
		HttpSession session = ContextHolderUtils.getSession();
		session.setAttribute("userRealName", user.getRealName());
		return "main/shortcut_main";
	}
	/**
	 * 解锁
	 */
	@RequestMapping(params = "unLock")
	@ResponseBody
	public AjaxJson unLock(HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		try {
		
			String userid=request.getParameter("userId");
			message="用户id:"+userid+"解锁成功";
			sessionService.unlockUser(userid);
			logService.addLogLogin(message,
					Globals.Log_Type_EXIT, null,LogUtil.logReqMap(request));
			j.setMsg(message);
			j.setSuccess(true);
		}catch (Exception e) {
			message="解锁失败:"+e.getMessage();
			j.setMsg(message);
			j.setSuccess(false);
		}
		return j;
	}
}
